package com.czy.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * telnet 模拟客户端工具
 * 1.telnet 127.0.0.1 10086
 * 2.Ctrl + ]
 * 3.send hello
 * @Author: czy
 */
public class BioServer {
    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        ServerSocket serverSocket = new ServerSocket(10086);//端口范围 1024-65535

        while (true){
            // 监听 等待客户端连接
            final Socket socket = serverSocket.accept();
            executorService.execute(()->{
                System.out.println("当前线程名称: "+Thread.currentThread().getName());
                handleConnect(socket);
            });
        }
    }

    public static void handleConnect(Socket socket){
        byte[] bytes = new byte[1024];

        try {
            InputStream inputStream = socket.getInputStream();
            while (true){
                int read = inputStream.read(bytes);
                if (read!=-1){
                    String text = new String(bytes, 0, read);
                    System.out.println(text);
                }else{
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
